package com.asurplus.system.service.impl;

import com.asurplus.common.layui.LayuiTableResult;
import com.asurplus.common.redis.RedisUtil;
import com.asurplus.common.utils.R;
import com.asurplus.system.pojo.RedisPojo;
import com.asurplus.system.service.SysRedisService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;

/**
 * @ClassName SysRedisServiceImpl
 * @Description
 * @Author Lizhou
 * @Date 2020-07-31 15:58:58
 **/
@Service
public class SysRedisServiceImpl implements SysRedisService {

    @Autowired
    private RedisUtil redisUtil;

    @Override
    public LayuiTableResult list(String perfix) {
        Set<String> data = redisUtil.getKeys((StringUtils.isBlank(perfix) ? "" : perfix) + "*");
        List<RedisPojo> list = new ArrayList<>();
        if (null != data && !data.isEmpty()) {
            RedisPojo redisPojo = null;
            for (String item : data) {
                redisPojo = new RedisPojo();
                redisPojo.setKey(item);
                redisPojo.setValue(String.valueOf(redisUtil.get(item)));
                list.add(redisPojo);
            }
        }
        return new LayuiTableResult<>(Long.parseLong("" + list.size()), list);
    }

    @Override
    public R add(RedisPojo redisPojo) {
        if (StringUtils.isBlank(redisPojo.getKey())) {
            return R.no("请输入键（key）");
        }
        if (null == redisPojo.getValue()) {
            return R.no("请输入值（value）");
        }
        redisUtil.set(redisPojo.getKey(), redisPojo.getValue());
        if (null != redisPojo.getExpire() && -1 != redisPojo.getExpire()) {
            redisUtil.setExpire(redisPojo.getKey(), redisPojo.getExpire());
        }
        return R.ok();
    }

    @Override
    public R delete(String key) {
        if (StringUtils.isBlank(key)) {
            return R.no("请输入键（key）");
        }
        String[] keyArr = key.split(",");
        List<String> list = Arrays.asList(keyArr);
        redisUtil.delBatch(list);
        return R.ok();
    }
}
